package com.stock.stockana.model;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.stock.stockana.constants.StorageConstants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by ljgsonx on 2016/1/22.
 */
public class StockService {

    private SQLiteDatabase mStockdb;

    private static StockService instance;

    private StockService(){}

    public static StockService getInstance() {
        if (instance == null) {
            return new StockService();
        }else {
            return instance;
        }
    }

    public static File copyDBFromAsset(Context context) {
        // copy asset database if not exist
        File db = new File(StorageConstants.STOCKDB_FILEPATH);
        if (db.exists()) {
            db.delete();
        }
        try {
            AssetManager assetManager = context.getAssets();
            InputStream is = assetManager.open(StorageConstants.STOCKDB_NAME);
            FileOutputStream fos = new FileOutputStream(db);
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
            }
            fos.flush();
            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return db;
    }

    private void openStockDB() {
        if(null == mStockdb){
            File db = new File(StorageConstants.STOCKDB_FILEPATH);
            if (db.exists()) {
                mStockdb = SQLiteDatabase.openDatabase(StorageConstants.STOCKDB_FILEPATH, null, SQLiteDatabase.OPEN_READONLY);
            }
        }
    }

    public void closeDB() {
        if (mStockdb != null) {
            mStockdb.close();
        }
    }

    public Cursor getStockByLikingMethod(String str){
        openStockDB();
        str = str.toUpperCase();
        Cursor c = null;
        if(null != mStockdb){
            c = mStockdb.rawQuery("select * from stock where _stockNum like ? or _stockName like ? or _firstLetter like ?"
                    , new String[]{"%" + str + "%","%" + str + "%","%" + str + "%"});
        }
        return c;
    }
}
